package ru.usu.gv.gui.frames;

import ru.usu.gv.core.I18nService;
import ru.usu.gv.gui.GUIUtilities;
import ru.usu.gv.gui.actions.AddGraphAction;
import ru.usu.gv.utils.generators.GraphGeneratorManager;
import ru.usu.gv.utils.generators.IGraphGenerator;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 @author Sergey Pupyrev 
 14.05.2007
 */

public class CreateNewGraphFrame extends JFrame
{
	public CreateNewGraphFrame()
	{
		setTitle(I18nService.get("frame.create_graph"));
		initComponents();
	}

	private JComboBox generatorsComboBox;
	private JPanel settingsPanel;

	private void initComponents()
	{

		JPanel commonPanel = new JPanel();
		commonPanel.setLayout(new BoxLayout(commonPanel, BoxLayout.Y_AXIS));

		generatorsComboBox = new JComboBox(GraphGeneratorManager.getInstance().getGenerators());
		commonPanel.add(generatorsComboBox);

		settingsPanel = new JPanel();
		commonPanel.add(settingsPanel);

		JPanel applyPanel = new JPanel();
		commonPanel.add(applyPanel);

		//apply
		JButton applyButton = new JButton(I18nService.get("frame.create_graph.ok"));
		applyButton.addActionListener(createApplyListener());
		applyPanel.add(applyButton);
		//applyButton.set

		//cancel
		JButton cancelButton = new JButton(I18nService.get("frame.create_graph.cancel"));
		applyPanel.add(cancelButton);
		cancelButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				dispose();
			}
		});

		generatorsComboBox.addItemListener(createItemListener());
		GraphGeneratorManager.getInstance().getGenerators()[0].customizePanel(settingsPanel);

		getContentPane().add(commonPanel);
		position();
	}

	private ActionListener createApplyListener()
	{
		return new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				IGraphGenerator selectedGenerator = (IGraphGenerator) generatorsComboBox.getSelectedItem();
				AddGraphAction action = new AddGraphAction(selectedGenerator.generate(settingsPanel));
				action.execute();

				dispose();
			}
		};
	}

	private ItemListener createItemListener()
	{
		return new ItemListener()
		{
			public void itemStateChanged(ItemEvent e)
			{
				if (ItemEvent.SELECTED == e.getStateChange())
				{
					IGraphGenerator selectedGenerator = (IGraphGenerator) generatorsComboBox.getSelectedItem();
					selectedGenerator.customizePanel(settingsPanel);

					position();
				}
			}
		};
	}

	private void position()
	{
		setResizable(false);
		pack();
		if (getWidth() < 300)
			setSize(300, getHeight());
		GUIUtilities.centralizeFrame(this);
	}
}
